#define _CRT_SECURE_NO_WARNINGS 1
#pragma warning(disable:6031)

#include "Queue.h"

void QueueInit(Queue* pQue)
{
	assert(pQue);

	pQue->head = pQue->tail = NULL;
}

static QueueNode* QueueNodeCreat(const QueueDataType val)
{
	QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));
	if (newnode == NULL)
	{
		printf("malloc err\n");
		exit(-1);
	}

	newnode->data = val;
	newnode->next = NULL;

	return newnode;
}

void QueuePush(Queue* pQue, const QueueDataType val)
{
	assert(pQue);

	QueueNode* newnode = QueueNodeCreat(val);
	if (pQue->head == NULL)
	{
		pQue->head = pQue->tail = newnode;
	}
	else
	{
		pQue->tail->next = newnode;
		pQue->tail = newnode;
	}
}

void QueuePop(Queue* pQue)
{
	assert(pQue);
	assert(!QueueEmpty(pQue));

	QueueNode* HeadNext = pQue->head->next;
	free(pQue->head);
	pQue->head = HeadNext;

	if (pQue->head == NULL)
	{
		pQue->tail = NULL;
	}
}

bool QueueEmpty(const Queue* pQue)
{
	assert(pQue);

	return pQue->head == NULL;
}

QueueDataType QueueFront(const Queue* pQue)
{
	assert(pQue);
	assert(!QueueEmpty(pQue));

	return pQue->head->data;
}

QueueDataType QueueBack(const Queue* pQue)
{
	assert(pQue);
	assert(!QueueEmpty(pQue));

	return pQue->tail->data;
}

size_t QueueSize(const Queue* pQue)
{
	assert(pQue);

	size_t count = 0;
	QueueNode* cur = pQue->head;

	while (cur)
	{
		++count;
		cur = cur->next;
	}

	return count;
}

void Queuedestroy(Queue* pQue)
{
	assert(pQue);

	QueueNode* cur = pQue->head;
	while (cur)
	{
		QueueNode* next = cur->next;
		free(cur);
		cur = next;
	}

	pQue->head = pQue->tail = NULL;
}